package com.key.oa.activity;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;

import com.key.keyleaderoa.R;
import com.key.oa.http.HttpLogin;
import com.key.oa.http.HttpUtil;
import com.key.oa.util.SysParams;
import com.key.oa.util.Util;

public class LoginActivity extends Activity implements OnClickListener {

	public ProgressDialog pDialog = null;
	
	private ImageButton loginButton = null;
	private ImageButton settingButton = null;
	
	private EditText usernameEditText = null;
	private EditText passwordEditText = null;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.key_login_menu);
        
        systemFinish();
        SysParams.loginActivity = this;
        
        initEditText();
        initLoginButton();
        initSettingButton();
        
        if( Util.sign == 1 && readUserData(Util.userdbpath) == true ) {
    		setTheUserData();
        } else if( Util.sign == 0 && checkUserDataFile() == true ) {
        	Intent gameIntent = new Intent(this,MainActivity.class);
			this.startActivity(gameIntent);
        }
        Util.sign = 0;
    }
	
	private boolean checkUserDataFile() {
		
		if( readUserData(Util.userdbpath) == true ) {
			setTheUserData();
			return checkUserDataHttp();
		}
		
		return false;
	}
	
	private void initEditText() {
		usernameEditText = (EditText) findViewById(R.id.usernameEditText);
		passwordEditText = (EditText) findViewById(R.id.passwordEditText);
	}
	
	private void initLoginButton() {
		
		loginButton = (ImageButton) findViewById(R.id.loginButton);
		loginButton.setOnClickListener(this);
		loginButton.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.key_login_down));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.key_login));
				}
				return false;
			}
		});
	}
	
	private void initSettingButton() {
		
		settingButton = (ImageButton) findViewById(R.id.settingButton);
		settingButton.setOnClickListener(this);
		settingButton.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.key_setting_down));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.key_setting));
				}
				return false;
			}
		});
	}

	public void onClick(View v) {

		Intent gameIntent = null;
		switch (v.getId()) {
		case R.id.loginButton:
			new Thread(new Runnable() {
				
				public void run() {
					// TODO Auto-generated method stub
					if( checkInput() == false ) {
						return;
					}
					if( sendHttpGet() == false ) {
						return;
					}
					//发送成功
					Message msg = new Message();
					msg.what = 3;
					handler.sendMessage(msg);
				}
			}).start();
			break;
		case R.id.settingButton:
			gameIntent = new Intent(this,SettingActivity.class);
			this.startActivity(gameIntent);
			break;
		default:
			break;
		}
	}
	
	
	private void setTheUserData() {
		if( Util.userdata.getUsername().length() != 0 &&
			Util.userdata.getPassword().length() != 0 ) {
			usernameEditText.setText(Util.userdata.getUsername());
			passwordEditText.setText(Util.userdata.getPassword());
		}
	}
	
	private boolean checkUserDataHttp() {
		
		if( Util.serverdata.getIP().length() == 0 ) {
			Util.toastPopWindow(this,"请设置ip地址");
			pDialog.dismiss();
			return false;
		}
		
		if( Util.serverdata.getPort().length() == 0 ) {
			Util.toastPopWindow(this,"请设置端口号");
			return false;
		}
		
		Message msg = new Message();
		msg.what = 4;
		handler.sendMessage(msg);
		
		String url = HttpLogin.get(Util.serverdata.getUriLogin()).trim();
		
		HttpUtil http = new HttpUtil();
		String result = http.get(url);
		
		if( result == null || result.length() == 0 ) {
			msg = new Message();
			msg.what = 2;
			handler.sendMessage(msg);
			return false;
		}
		if( result.equals(Util.netsure) ) {
			if(pDialog != null) {
				pDialog.cancel();
			}
			return true;
		}
		msg = new Message();
		msg.what = 1;
		handler.sendMessage(msg);
		
		return false;
	}
	
	public Handler handler = new Handler() {
		public AlertDialog.Builder dg = null;
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if(pDialog != null) {
					pDialog.cancel();
				}
				dg = new AlertDialog.Builder(LoginActivity.this);
				dg.setTitle("登录失败");
				String message = "用户名或密码错误";
				dg.setMessage(message);
				dg.show();
				break;
			case 2:
				if (pDialog != null) {
					pDialog.cancel();
				}
				dg = new AlertDialog.Builder(LoginActivity.this);
				dg.setTitle("登录失败");
				message = "检查网络等错误";
				dg.setMessage(message);
				dg.show();
				break;
			case 3:
				Intent gameIntent = null;
				gameIntent = new Intent(LoginActivity.this,MainActivity.class);
				startActivity(gameIntent);
				finish();
				break;
			case 4:
				pDialog = new ProgressDialog(LoginActivity.this);
				pDialog.setTitle("提示");
				pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				pDialog.setMessage("正在登录中，请稍后...");
				pDialog.setIndeterminate(true);
				pDialog.show();
				break;
			default:
				break;
			}
		}
	};
	
	private boolean sendHttpGet() {
		
		if( checkUserDataHttp() == false ) {
			return false;
		}
		
		if( writeUserData(Util.userdbpath) == false ) {
			Util.toastPopWindow(this, "本地保存账号密码失败");
		}
		
		return true;
	}
	
	private boolean checkInput() {
		
		String username = usernameEditText.getText().toString().trim();
		String password = passwordEditText.getText().toString().trim();
		
		if( username.length() == 0 ) {
			Util.toastPopWindow(this,"账号不能为空");
			return false;
		}
		
		if( password.length() == 0 ) {
			Util.toastPopWindow(this,"密码不能为空");
			return false;
		}
		
		Util.userdata.setUsername(username);
		Util.userdata.setPassword(password);
		
		return true;
	}
	
	private boolean writeUserData( String path ) {
		
		try {
			
			FileOutputStream fos = this.openFileOutput(path,Context.MODE_PRIVATE);
			
			byte[] username = Util.userdata.getUsername().getBytes();
			byte[] len = new byte[1];
			len[0] = (byte) username.length;
			fos.write(len);
			fos.write(username);
			
			byte[] password = Util.userdata.getPassword().getBytes();
			len[0] = (byte) password.length;
			fos.write(len);
			fos.write(password);
			
			fos.close();
			
			return true;
		} catch (Exception e) {
            e.printStackTrace();
            return false;
        }
	}
	
	private boolean readUserData( String path ) {
		
		try {
			
			/*
			 * 判断文件存在需要全路径，这里使用try catch.
			 * */
			// path => data/data/com.ql.app/files/stockDic.dat
			// File file = new File(path);
			
			FileInputStream fin = openFileInput(path);
			
			byte[] len = new byte[1];
			if( fin.read(len) == -1 ) {
				return false;
			}
			byte[] user = new byte[len[0]];
			if( fin.read(user) == -1 ) {
				return false;
			}
			
			if( fin.read(len) == -1 ) {
				return false;
			}
			byte[] pass = new byte[len[0]];
			if( fin.read(pass) == -1 ) {
				return false;
			}
			fin.close();
			
			Util.userdata.setUsername(new String(user));
			Util.userdata.setPassword(new String(pass));
			
			return true;
			
		} catch (Exception e) {
            e.printStackTrace();
            return false;
        }
	}
	
	private void systemFinish() {
		if( SysParams.intentMain != null ) {
			stopService(SysParams.intentMain);
		}
		if( SysParams.loginActivity != null ) {
			SysParams.loginActivity.finish();
		}
		if( SysParams.mainActivity != null ) {
			SysParams.mainActivity.finish();
		}
		if( SysParams.settingActivity != null ) {
			SysParams.settingActivity.finish();
		}
		if( SysParams.uncheckedActivity != null ) {
			SysParams.uncheckedActivity.finish();
		}
	}
	
	@Override
	public boolean onKeyDown(int kCode, KeyEvent kEvent) {

		if (kCode == KeyEvent.KEYCODE_BACK) {
			systemFinish();
			super.finish();
			this.finish();
			destory();
            return true;
		} 
		return super.onKeyDown(kCode, kEvent);
	}
	
	private void destory() {
    	System.exit(0);
    }
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
}
 